package com.hcms.common.service.impl;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.hcms.common.dto.CaptchaResult;
import com.hcms.common.service.ICaptchaService;
import com.hcms.common.service.IRedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

public class CaptchaServiceImpl implements ICaptchaService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //缓存保存10分钟
    @Value("${redis.expire.captcha:180}")
    private long expire;

    @Autowired
    private IRedisService iRedisService;

    @Override
    public CaptchaResult generator(Integer width, Integer height) {
        logger.info("Run method: generator(), width={}, height={}", width, height);
        AbstractCaptcha captcha = CaptchaUtil.createCircleCaptcha(width, height, 4, 10);
        String code = captcha.getCode();
        String imageBase64Data = captcha.getImageBase64Data();
        String codeKey = "CAPTCHA:" + UUID.fastUUID().toString().replace("-", "").toUpperCase();
        //保存到缓存中
        logger.info("Cache expiration time: {}", expire);
        iRedisService.set(codeKey, code, expire);
        logger.info("Save the verification code to the cache");
        return CaptchaResult.builder()
                .codeKey(codeKey)
                .codeImage(imageBase64Data)
                .build();
    }

    @Override
    public boolean verify(String codeKey, String inputCode) {
        logger.info("Run method: verify(), codeKey={}, inputCode={}", codeKey, inputCode);
        if (StrUtil.isEmpty(codeKey) || StrUtil.isEmpty(inputCode)) {
            logger.error("CodeKey or InputCode is empty");
            return false;
        }
        String cacheCode = (String) iRedisService.get(codeKey);
        if (StrUtil.isEmpty(cacheCode)) {
            logger.error("CacheCode is empty");
            return false;
        }
        return inputCode.equalsIgnoreCase(cacheCode);
    }

    @Override
    public boolean delete(String codeKey) {
        logger.info("Run method: delete(), codeKey={}", codeKey);
        return iRedisService.del(codeKey);
    }

}
